<template>
  <el-card>
    <el-form class="form" :inline="true">
      <el-form-item label="用户名">
        <el-input
          v-model="searchValue"
          style="width: 240px"
          placeholder="输入用户名"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search" :disabled="!searchValue">
          搜索
        </el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>

  <el-card style="margin-top: 25px">
    <div>
      <el-button @click="addUser" type="primary" v-has="'btn.User.add'">
        添加用户
      </el-button>
      <el-button @click="deleteUsers">批量删除</el-button>
    </div>
    <el-table
      ref="tableComponent"
      :data="userList"
      style="margin-top: 25px"
      border
    >
      <el-table-column width="40" type="selection"></el-table-column>
      <el-table-column label="#" type="index"></el-table-column>
      <el-table-column label="id" prop="id" width="100"></el-table-column>
      <el-table-column
        label="用户名"
        prop="username"
        width="120"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column label="用户名称" prop="name"></el-table-column>
      <el-table-column
        label="用户角色"
        prop="roleName"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column label="创建时间" prop="createTime"></el-table-column>
      <el-table-column label="更新时间" prop="updateTime"></el-table-column>
      <el-table-column label="操作" width="400">
        <template #="{ row, index }">
          <el-button
            type="primary"
            icon="User"
            @click="openManageDrawer(row)"
            v-has="'btn.User.assgin'"
          >
            分配角色
          </el-button>
          <el-button
            type="primary"
            icon="Edit"
            @click="updateUser(row)"
            v-has="'btn.User.update'"
          >
            编辑
          </el-button>

          <el-popconfirm @confirm="deleteUser(row)" title="确定要删除该用户?">
            <template #reference>
              <el-button type="primary" icon="Delete" v-has="'btn.User.remove'">
                删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="margin-top: 25px"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[5, 7, 9, 12]"
      layout=" prev, pager, next, jumper,->,total, sizes"
      :total="total"
      @size-change="getUserListFromServer"
      @current-change="getUserListFromServer"
    />
  </el-card>
  <el-drawer v-model="isShowDrawer" direction="rtl">
    <template #header>
      <h4>{{ drawerTitle }}</h4>
    </template>
    <template #default>
      <el-form
        ref="formComponent"
        label-width="100px "
        :model="userParam"
        :rules="rules"
      >
        <el-form-item label="用户姓名" prop="username">
          <el-input
            v-model="userParam.username"
            placeholder="请输入用户姓名"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" prop="name">
          <el-input
            v-model="userParam.name"
            placeholder="请输入用户昵称"
          ></el-input>
        </el-form-item>

        <el-form-item
          label="用户密码"
          prop="password"
          v-if="userParam.id ? false : true"
        >
          <el-input
            v-model="userParam.password"
            placeholder="请输入用户密码"
          ></el-input>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="isShowDrawer = false">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </div>
    </template>
  </el-drawer>

  <el-drawer v-model="manageRoleDrawer" direction="rtl">
    <template #header>
      <h4>分配角色</h4>
    </template>
    <template #default>
      <el-form>
        <el-form-item label="用户名">
          <el-input v-model="userParam.username" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-checkbox
            v-model="checkAll"
            :indeterminate="isIndeterminate"
            @change="handleCheckAllChange"
          >
            全选
          </el-checkbox>
          <el-checkbox-group
            v-model="assignRoles"
            @change="handleCheckedCitiesChange"
          >
            <el-checkbox
              v-for="(role, index) in allRolesList"
              :key="role.id"
              :label="role.id"
              :value="role"
            >
              {{ role.roleName }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="manageRoleDrawer = false">取消</el-button>
        <el-button type="primary" @click="confirmManageRole">确认</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import {
  reqAssignRoleForUser,
  reqCreateAccount,
  reqRemoveUser,
  reqRemoveUsers,
  reqRoleToAssign,
  reqUserList,
} from '@/api/user'
import { IAssignRole, IUserInfo } from '@/api/user/type'
import userServer from './user.server'
import { ElMessage, type FormInstance, type TableInstance } from 'element-plus'
import loginRules from '@/views/login/login.rules'
let { addUserTitle, updateUserTitle, drawerTitle } = userServer()
let tableComponent = ref<TableInstance>()
let currentPage = ref<number>(1)
let total = ref<number>(10)
let pageSize = ref<number>(5)
let searchValue = ref<string>('')
let userList = ref<IUserInfo[]>([])
let isShowDrawer = ref<boolean>(false)
let formComponent = ref<FormInstance>()
let manageRoleDrawer = ref(false)
let assignRoles = ref<any[]>([])
let userParam = reactive<IUserInfo>({
  id: '',
  name: '',
  phone: '',
  roleName: '',
})
let allRolesList = ref<IAssignRole[]>([])
let { rules } = loginRules()

onMounted(() => {
  getUserListFromServer()
})
const deleteUser = async (data) => {
  try {
    let result = await reqRemoveUser(data.id)
    if (result.code == 200) {
      getUserListFromServer()
    }
  } catch (error) {
    console.log(error)
  }
}
const getUserListFromServer = async () => {
  try {
    let result = await reqUserList(currentPage.value, pageSize.value)
    if (result.code == 200) {
      userList.value = result.data.records
      total.value = result.data.total
    }
  } catch (error) {
    console.log(error)
  }
}
const updateUser = (data) => {
  updateUserTitle()
  isShowDrawer.value = true
  formComponent.value?.clearValidate()
  userParam = data
}
const addUser = () => {
  userParam = reactive<IUserInfo>({
    id: '',
    name: '',
    phone: '',
    roleName: '',
  })
  formComponent.value?.clearValidate()
  addUserTitle()
  isShowDrawer.value = true
}
const reset = () => {
  searchValue.value = ''
  search()
}
const save = async () => {
  let result = await formComponent.value.validate()
  if (result) {
    reqCreateAccount(userParam).then((res) => {
      getUserListFromServer()
      isShowDrawer.value = false
      window.location.reload()
    })
  }
}
const confirmManageRole = async () => {
  try {
    let result = await reqAssignRoleForUser({
      roleIdList: assignRoles.value.map((role) => role.id),
      userId: userParam.id as number,
    })
    if (result.code == 200) {
      getUserListFromServer()
      manageRoleDrawer.value = false
    }
  } catch (error) {
    console.log(error)
  }
}

const openManageDrawer = async (data) => {
  manageRoleDrawer.value = true
  Object.assign(userParam, data)
  try {
    let result = await reqRoleToAssign(data.id)
    if (result.code == 200) {
      allRolesList.value = result.data.allRolesList
      assignRoles.value = result.data.assignRoles
      isIndeterminate.value = !(assignRoles.value.length == 0)
    }
  } catch (error) {
    console.log(error)
  }
}

const checkAll = ref(false)
const isIndeterminate = ref(true)
const search = async () => {
  try {
    let result = await reqUserList(
      currentPage.value,
      pageSize.value,
      searchValue.value,
    )
    if (result.code == 200) {
      userList.value = result.data.records
    }
  } catch (error) {
    console.log(error)
  }
}
const handleCheckAllChange = (val: boolean) => {
  assignRoles.value = val ? allRolesList.value : []
  isIndeterminate.value = false
}
const handleCheckedCitiesChange = (value: string[]) => {
  const checkedCount = value.length
  checkAll.value = checkedCount === allRolesList.value.length
  isIndeterminate.value =
    checkedCount > 0 && checkedCount < allRolesList.value.length
}

const deleteUsers = () => {
  console.log(tableComponent.value?.getSelectionRows())
  let seletedRows: IAssignRole[] = tableComponent.value?.getSelectionRows()
  console.log(seletedRows.map((role) => role.id))

  reqRemoveUsers(seletedRows.map((role) => role.id)).then((res) => {
    console.log(res)
    if (res.code == 200) {
      ElMessage({ type: 'success', message: '删除成功' })
      getUserListFromServer()
    }
  })
}
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  align-items: center;
  justify-content: space-between;
  .el-form-item {
    margin: 0;
  }
}
</style>
